package Yangtz.Cs.Reader.Controller.Login;

import Yangtz.Cs.Entity.ReaderBean;
import Yangtz.Cs.Service.ReaderService;
import Yangtz.Cs.Utils.DataTransmissionUtil;
import Yangtz.Cs.Utils.SetEncodingUtil;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {

    private JSONObject jsonObject1=new JSONObject();
    private JSONObject jsonObject2=new JSONObject();

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置请求编码、响应方式和编码方式
        SetEncodingUtil.SetEncoding(request, response);

        //获取android发来的json格式数据
        jsonObject1=DataTransmissionUtil.gainJsonFromAndroid(request);

        //创建ReaderBean对象，负责接受赋值后的reader对象
        ReaderBean reader1;

        //负责传参
        ReaderBean reader2=new ReaderBean();
        reader1=setData(reader2);

        ReaderService rs=new ReaderService();
        if(rs.insert(reader1)){
            jsonObject2.put("reg_tag","success");
            DataTransmissionUtil.sendJsonToAndroid(jsonObject2,response);
        }else{
            jsonObject2.put("reg_tag","failed");
            DataTransmissionUtil.sendJsonToAndroid(jsonObject2,response);
        }

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    public ReaderBean setData(ReaderBean reader){
        reader.setRdID(jsonObject1.optString("rdID"));
        reader.setRdName(jsonObject1.optString("rdName"));
        reader.setRdSex(jsonObject1.optString("rdSex"));

        //读者类型在android写的是1(教师),在这里通过获取字串，再转换成int类型插入数据库
        reader.setRdType(Integer.parseInt(jsonObject1.optString("rdType").substring(0,1)));
        reader.setRdDept(jsonObject1.optString("rdDept"));
        reader.setRdPhone(jsonObject1.optString("rdPhone"));
        reader.setRdEmail(jsonObject1.optString("rdEmail"));
        reader.setRdPWd(jsonObject1.optString("rdPwd"));
        reader.setRdAdminRoles(jsonObject1.optString("rdAdmin"));
        return reader;
    }

}
